<script>
export default {
  name: 'ChangeRoleDialog'
}
</script>
<script setup>
import $API from '@/api/index'
import { UsersModel } from '@/model/Users.js'
import { ElMessage } from 'element-plus'
import { ref, getCurrentInstance, onUnmounted } from 'vue'

const $emits = defineEmits(['confirm', 'close'])

const form = new UsersModel()

const { row } = defineProps(['row'])

form.setData({
  ...row
})

// 用户信息表单DOM
const userInfoEditorRef = ref()
// 用户信息表单在自定义校验规则
const validateName = function (rule, value, cb) {
  if (value.length < 4) {
    cb(new Error('名字至少4位'))
  } else {
    cb()
  }
}
const validateUsername = function (rule, value, cb) {
  if (value.length < 4) {
    cb(new Error('名称至少4位'))
  } else {
    cb()
  }
}
const validatePassword = function (rule, value, cb) {
  if (value.length < 6) {
    cb(new Error('密码至少6位'))
  } else {
    cb()
  }
}
const userInfoEditorValidate = {
  name: [{ required: true, validator: validateName, trigger: 'change' }],
  username: [{ required: true, validator: validateUsername, trigger: 'change' }],
  password: [{ required: true, validator: validatePassword, trigger: 'change' }]
}
// 关闭用户信息编辑抽屉
const closeUserInfoEditor = function () {
  userInfoEditorRef.value.resetFields()
  form.vm.data = {
    name: '',
    username: '',
    password: ''
  }
}

// 保存用户信息编辑抽屉
const save = async function (formRef) {
  if (!formRef) return
  try {
    await formRef.validate()
    await form.update()
    if (form.vm.status === 2) $emits('confirm')
  } catch (error) {
    console.log(error)
    ElMessage.error('更新失败')
  }
}
</script>

<template>
  <el-form
    label-width="80px"
    :model="form.vm.data"
    ref="userInfoEditorRef"
    :rules="userInfoEditorValidate"
  >
    <el-form-item
      label="用户姓名"
      prop="name"
    >
      <el-input
        v-model="form.vm.data.name"
        placeholder="请填写用户姓名"
      />
    </el-form-item>
    <el-form-item
      label="用户名称"
      prop="username"
    >
      <el-input
        v-model="form.vm.data.username"
        placeholder="请填写用户名称"
      />
    </el-form-item>
    <el-form-item
      label="用户密码"
      prop="password"
      v-if="!form.vm.data?.id"
    >
      <el-input
        v-model="form.vm.data.password"
        placeholder="请填写用户密码"
      />
    </el-form-item>
  </el-form>
  <div>
    <el-button @click="$emits('close')">取消</el-button>
    <el-button
      type="primary"
      @click="save(userInfoEditorRef)"
    >
      确定
    </el-button>
  </div>
</template>

<style scoped lang="scss">
// start
</style>
